package com.share.example.bcs.client.client;

import com.share.example.bcs.client.client.tcp.TcpClientHandler;
import com.share.example.bcs.common.protocol.tcp.MsgBodyDecoder;
import com.share.example.bcs.common.protocol.tcp.MsgBodyEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class NettyClient {
    private static String ip = "127.0.0.1";
    private static int port = 12345;

    private EventLoopGroup loopGroup = null;

    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient();
        nettyClient.init();//建立连接
        nettyClient.loopGroup.shutdownGracefully();//关闭应用
    }

    @PostConstruct
    public void init() {
        // 客户端就只需要创建一个 线程组了
        loopGroup = new NioEventLoopGroup();

        // 创建 启动器
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 设置相关的参数
            bootstrap.group(loopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new MsgBodyDecoder());
                            socketChannel.pipeline().addLast(new TcpClientHandler());
                            socketChannel.pipeline().addLast(new MsgBodyEncoder());
                        }
                    });
            // 连接服务
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            // 对服务关闭 监听
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("服务连接异常", e);
        } finally {
            loopGroup.shutdownGracefully();
        }
    }
}
